class Alipay::PaymentNotificationsController < ApplicationController

  def create
    notification_params = params.except(*request.path_parameters.keys)
    if ALIPAY_CLIENT.verify?(notification_params)
      order = Order.find_by(order_num: notification_params[:out_trade_no])
      PaymentNotification.create(order_history_id: order.id, payment_method: 'alipay', raw_content: notification_params.to_json, request_id: request.request_id)
      send(notification_params[:trade_status].downcase, order, notification_params)
      # TODO notify mobile through websocket
      render plain: 'success', status: :created
    else
      render plain: 'fail', status: :unprocessable_entity
    end
  end

  private

  def wait_buyer_pay(*); end
  alias trade_pending wait_buyer_pay

  def trade_closed(order, *)
    # expire_cache "orders:#{order.payer.id}:index:*", "orders:#{order.payer.id}:#{order.id}" do
      order.reject unless order.succeeded?
    # end
  end

  def trade_success(order, params)
    # expire_cache "orders:#{order.payer.id}:index:*", "orders:#{order.payer.id}:#{order.id}" do
      order.confirm(params[:trade_no], params[:buyer_logon_id]) unless order.paid?
    # end
  end
  alias trade_finished trade_success
end
